#include <cassert>
#include <rtpudpv4transmitter.h>
#include <rtpsessionparams.h>
#include <rtpipv4address.h>
#include "RTPSender.h"

using namespace ipsound;

void checkerror( int rtperr )
{
	assert ( rtperr >= 0 );
}

RTPSender::RTPSender( MutexBuffer* buffer )
:buffer( buffer )
,srcPort( 4000 )
,dstPort( 3000 )
,session( 0 )
,samplesPerSec( 8000.0 )
,packetSize( 500 )
,bitsPerSample( 16 )
{
	dstIp = inet_addr( "127.0.0.1" );
	assert( dstIp != INADDR_NONE );
	dstIp = ntohl( dstIp );
}

void* RTPSender::Thread()
{
	WSAStartup( MAKEWORD(2,2), &dat );
	Init();
	ThreadStarted();

	void* buf = malloc(packetSize);
	
	while ( true )
	{
		size_t read = buffer->Read(buf, packetSize);
		if (read > 0)
		{
			assert(session);
			session->SendPacket(buf, read);
		}
		RTPTime::Wait( packetSize / (samplesPerSec * bitsPerSample / 8) );
	}

	free(buf);
	WSACleanup();
	return 0;
}

RTPSender::~RTPSender()
{
	session->BYEDestroy( RTPTime( 5.0 ), "Time's up", 9 );
	delete session;
}

void RTPSender::Init()
{	
	session = new RTPSession();
	RTPUDPv4TransmissionParams transparams;
	RTPSessionParams sessparams;

	sessparams.SetOwnTimestampUnit( 1.0 / samplesPerSec );
	sessparams.SetAcceptOwnPackets( false );
	transparams.SetPortbase( srcPort );
	int status = session->Create( sessparams, &transparams );
	checkerror( status );

	RTPIPv4Address addr( dstIp, dstPort );

	status = session->AddDestination( addr );
	checkerror( status );

	session->SetDefaultMark(false);
	session->SetDefaultPayloadType(0);
	session->SetDefaultTimestampIncrement( (uint32_t)(packetSize / samplesPerSec) );
}
